import json
import os
from datetime import datetime, date
from typing import Dict, List, Optional
import random

class WordStudyManager:
    def __init__(self, data_dir: str = "data/word_banks"):
        """初始化单词学习管理器
        
        Args:
            data_dir: 词库文件存储目录
        """
        # 获取项目根目录的绝对路径
        self.root_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
        self.data_dir = os.path.join(self.root_dir, data_dir)
        self.current_wordbank = None  # 当前使用的词库名称
        self.words_data: List[Dict] = []  # 词库中的单词数据
        self.user_progress: Dict[str, Dict] = {}  # 用户学习进度
        
        # 确保数据目录存在
        user_data_dir = os.path.join(self.root_dir, "data", "user_data")
        os.makedirs(user_data_dir, exist_ok=True)
        self._load_user_progress()
    
    def load_wordbank(self, wordbank_name: str) -> bool:
        """加载指定的词库
        
        Args:
            wordbank_name: 词库文件名（不含扩展名）
            
        Returns:
            是否成功加载
        """
        file_path = os.path.join(self.data_dir, f"{wordbank_name}.json")
        try:
            if os.path.exists(file_path):
                with open(file_path, 'r', encoding='utf-8') as f:
                    data = json.load(f)
                    self.words_data = data["words"]
                self.current_wordbank = wordbank_name
                print(f"成功加载词库 {wordbank_name}，共 {len(self.words_data)} 个单词")
                return True
            return False
        except Exception as e:
            print(f"加载词库失败: {str(e)}")
            return False
    
    def _load_user_progress(self):
        """加载用户学习进度"""
        progress_file = os.path.join(self.root_dir, "data", "user_data", "word_progress.json")
        if os.path.exists(progress_file):
            with open(progress_file, 'r', encoding='utf-8') as f:
                self.user_progress = json.load(f)
    
    def _save_user_progress(self):
        """保存用户学习进度"""
        progress_file = os.path.join(self.root_dir, "data", "user_data", "word_progress.json")
        with open(progress_file, 'w', encoding='utf-8') as f:
            json.dump(self.user_progress, f, ensure_ascii=False, indent=2)
    
    def get_word_info(self, word: str) -> Optional[Dict]:
        """获取单词信息
        
        Args:
            word: 要查询的单词
            
        Returns:
            包含单词信息的字典，如果未找到则返回 None
        """
        for word_data in self.words_data:
            if word_data["word"] == word:
                return word_data
        return None
    
    def get_all_words(self) -> List[Dict]:
        """获取词库中的所有单词
        
        Returns:
            单词信息字典列表
        """
        return self.words_data
    
    def update_word_progress(self, word: str, correct: bool):
        """更新单词学习进度
        
        Args:
            word: 单词
            correct: 是否正确
        """
        if word not in self.user_progress:
            self.user_progress[word] = {
                "total_attempts": 0,
                "correct_attempts": 0,
                "last_review": None,
                "next_review": None,
                "mastery_level": 0,  # 0-100 的掌握度
                "wordbank": self.current_wordbank
            }
        
        progress = self.user_progress[word]
        progress["total_attempts"] += 1
        if correct:
            progress["correct_attempts"] += 1
        
        # 更新掌握度
        accuracy = progress["correct_attempts"] / progress["total_attempts"]
        progress["mastery_level"] = min(100, int(accuracy * 100))
        
        # 更新复习时间
        progress["last_review"] = datetime.now().isoformat()
        
        # 根据艾宾浩斯遗忘曲线设置下次复习时间
        if progress["mastery_level"] < 60:
            # 掌握度低，1天后复习
            next_review = datetime.now().date() + date.resolution
        elif progress["mastery_level"] < 80:
            # 掌握度中等，3天后复习
            next_review = datetime.now().date() + date.resolution * 3
        else:
            # 掌握度高，7天后复习
            next_review = datetime.now().date() + date.resolution * 7
            
        progress["next_review"] = next_review.isoformat()
        
        self._save_user_progress()
    
    def get_word_progress(self, word: str) -> Optional[Dict]:
        """获取单词的学习进度
        
        Args:
            word: 单词
            
        Returns:
            进度信息字典，如果未找到则返回 None
        """
        return self.user_progress.get(word)
    
    def get_words_to_review(self) -> List[Dict]:
        """获取今天需要复习的单词列表
        
        Returns:
            需要复习的单词信息列表
        """
        today = date.today().isoformat()
        review_words = []
        
        for word, progress in self.user_progress.items():
            if (progress["wordbank"] == self.current_wordbank and
                progress["next_review"] and progress["next_review"] <= today):
                word_info = self.get_word_info(word)
                if word_info:
                    review_words.append(word_info)
        
        return review_words
    
    def get_daily_new_words(self, count: int = 20) -> List[Dict]:
        """获取每日新单词
        
        Args:
            count: 新单词数量
            
        Returns:
            新单词信息列表
        """
        # 获取所有未学习的单词
        learned_words = {
            word for word, progress in self.user_progress.items()
            if progress["wordbank"] == self.current_wordbank
        }
        
        new_words = []
        for word_data in self.words_data:
            if word_data["word"] not in learned_words:
                new_words.append(word_data)
        
        # 随机返回指定数量的新单词
        random.shuffle(new_words)
        return new_words[:count]
    
    def get_learning_stats(self) -> Dict:
        """获取学习统计信息
        
        Returns:
            统计信息字典
        """
        if not self.current_wordbank:
            return {}
            
        total_words = len(self.words_data)
        learned_words = sum(1 for p in self.user_progress.values() 
                          if p["wordbank"] == self.current_wordbank)
        mastered_words = sum(1 for p in self.user_progress.values()
                           if p["wordbank"] == self.current_wordbank 
                           and p["mastery_level"] >= 80)
                           
        return {
            "total_words": total_words,
            "learned_words": learned_words,
            "mastered_words": mastered_words,
            "progress_percentage": round(learned_words / total_words * 100, 2)
        } 